#pragma once


#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <fstream>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

using namespace std;

#define SEP "\r\n"
#define SEP_LEN strlen(SEP)

const string default_url = "./wwwroot";
const string home_page = "index.html";
const string html_404 = "./wwwroot/404.html";

//method url version\r\n
string getLine(string &in)
{
    int pos = in.find(SEP);
    if (pos == string::npos)
        return nullptr;
    string line = in.substr(0, pos);
    in.erase(0, pos + SEP_LEN);
    return line;
}

bool readFile(const string& path, char* buffer, int size)
{
    ifstream ifs(path.c_str(), ios::binary);
    if (!ifs.is_open())
        return false;
    ifs.read(buffer, size);
    ifs.close();
    return true;
}

//参照content-type对照表
string suffixToType(const string& suffix)
{
    string type;
    if (suffix == ".html")
        type = "text/html";
    else if (suffix == ".jpg")
        type = "application/x-jpg";
    else if (suffix == ".png")
        type = "application/x-png";
    else
        type = "unknown type";
    return type;
}

struct httpRequest
{
    void parse()
    {
        string line = getLine(inbuffer);
        if (line.empty())
            return;
        stringstream ss(line);
        ss >> method >> url >> version;
        path = default_url;//设置资源根目录
        path += url;//客户端请求的资源路径
        if (path[path.size() - 1] == '/')//如果客户端没有指定请求的资源 则默认请求首页
            path += home_page;
        int pos = path.rfind(".");
        if (pos == string::npos)
            suffix = ".html";
        else
            suffix = path.substr(pos);
        struct stat st;
        if (stat(path.c_str(), &st) == 0)
            size = st.st_size;
        else
            size = -1;
    }

    string inbuffer;
    // string reqline;//请求行
    // vector<string> reqheader;//http请求报头由多行属性信息组成
    // string body;//请求正文

    string method;
    string url;
    string version;
    string path;
    string suffix;
    int size;
};

struct httpResponse
{
    string outbuffer;
};
